<?php


namespace App\Controller;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Request\GetCodeForSignUpRequest;
use App\Request\LoginRequest;
use App\Request\SignUpRequest;
use App\Service\Instance\JwtInstance;
use App\Service\MailService;
use App\Service\UserService;
use Hyperf\Di\Annotation\Inject;

/**
 * Class MailController
 * @package App\Controller
 */
class UserController extends AbstractController
{

    /**
     * @var UserService
     */
    #[Inject]
    protected UserService $userService;


    public function test()
    {
        $token = $this->request->input('token');
        $jwtInstance = JwtInstance::instance();
        try {
            $jwtInstance->decode($token);
        } catch (\Throwable $e) {

        }

        $uid = $jwtInstance->getId();
        if (empty($uid)) {
            throw new BusinessException(ErrorCode::FORBIDDEN);
        }

        return $this->response->success([
            'uid' => $uid,
        ]);
    }

    /**
     * 登陆
     * @param LoginRequest $loginRequest
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function login(LoginRequest $loginRequest){
        $validated = $loginRequest->validated();
        [$user,$token] = $this->userService->login($validated['email'],$validated['password']);
        return $this->response->success([
            'user' => $user,
            'token' => $token
        ]);
    }

    /**
     * 获取邮箱验证码
     */
    public function signup(SignUpRequest $signUpRequest)
    {
        // 获取已验证的数据
        $validated = $signUpRequest->validated();
        [$user, $token] = $this->userService->signup($validated);
//        return $this->response->success();
        return $this->response->success([
            'user' => $user,
            'token' => $token,
        ]);
    }
}